package org.springframework.prospring.ticket.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.prospring.ticket.dao.CityDAO;
import org.springframework.prospring.ticket.dao.ProvinceDAO;
import org.springframework.prospring.ticket.domain.location.City;
import org.springframework.prospring.ticket.domain.location.Province;
import org.springframework.prospring.ticket.exception.BusinessException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;

import java.util.Collection;

/**
 * This class interacts with Spring and Hibernate to save and
 * retrieve User objects.
 *
 * @author Alexis Quiros
 */
public class ProvinceDAOHibernate extends HibernateDaoSupport implements ProvinceDAO {
    private static Log log = LogFactory.getLog(ProvinceDAOHibernate.class);

    public ProvinceDAOHibernate() {
        super();
        if (log.isDebugEnabled()) {
            log.debug("in ProvinceDAOHibernate Constructor");
        }
    }

    public Province findProvince(Long provinceId) {
        if (log.isDebugEnabled()) {
            log.debug("finding Province id: " + provinceId);
        }

        Province province = (Province)getHibernateTemplate().load(Province.class, provinceId);

        

        return province;
    }

    public Collection <City> findCitiesByProvince(Long provinceId){
        if (log.isDebugEnabled()) {
            log.debug("Finding Cities for Province id: " + provinceId);
        }

        Province province = this.findProvince(provinceId);
        Collection<City> cities = province.getCities();
        return cities;
    }

    public Collection<Province> findAllProvinces() {
        if (log.isDebugEnabled()) {
            log.debug("finding all Provinces ");
        }

        Collection<Province> provinces = getHibernateTemplate().find("from Province");
        return provinces;
    }

    public void saveProvince(Province province) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Saving Province: " + province);
        }

        if (StringUtils.isEmpty(province.getName())) {
            String message = "The name is required, name="+province.getName();
            log.info(message);
            throw new BusinessException(message);
        }

        getHibernateTemplate().saveOrUpdate(province);

        if (log.isDebugEnabled()) {
            log.debug("provinceId set to: " + province.getId());
        }
    }

    public void removeProvince(Long provinceId) {
        if (log.isDebugEnabled()) {
            log.debug("removing Province id: " + provinceId);
        }

        Object province = getHibernateTemplate().load(Province.class, provinceId);
        getHibernateTemplate().delete(province);
    }


}
